'use strict'

import axios from 'axios'
import { Message } from 'element-ui'


const baseURL = process.env.NODE_ENV === 'production' ? "http://data.e-fts.cn/api/" : '/api';
axios.defaults.baseURL = baseURL

axios.interceptors.request.use(config => {
  let token = sessionStorage.getItem("token")
  if (token) {
    config.headers = {
      'token': token,
    };
  }
  return config
}, error => {
  Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})
function checkStatus(response) {
  // loading
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    if (response.data.h.code === 0) {
      return response
      // 如果不需要除了data之外的数据，可以直接 return response.data
    }
    if (response.data.h.code !== 0) {
      Message({
        message: response.data.h.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // 如果不需要除了data之外的数据，可以直接 return response.data
    }
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: response.msg
  }
}
export default {
  post(url, data) {
    return axios({
      method: 'post',
      url,
      data,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  },
  put(url, data) {
    return axios({
      method: 'put',
      url,
      data,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  },
  get(url, params) {
    return axios({
      method: 'get',
      url,
      params, // get 请求时带的参数
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  }
}
